package org.lpye.shiroRedis;

import java.util.Iterator;
import java.util.Set;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.ShardedJedis;
import redis.clients.jedis.ShardedJedisPool;

public class MyRedisManager {
	
	// 0 - never expire
	private int expire = 0;
	
	private ShardedJedisPool jedisPool;
	
	public MyRedisManager(){
		
	}
	
	/**
	 * get value from redis
	 * @param key
	 * @return
	 */
	public byte[] get(byte[] key){
		byte[] value = null;
		ShardedJedis jedis = jedisPool.getResource();
		try{
			value = jedis.get(key);
		}finally{
			jedis.close();
		}
		return value;
	}
	
	/**
	 * set 
	 * @param key
	 * @param value
	 * @return
	 */
	public byte[] set(byte[] key,byte[] value){
		ShardedJedis jedis = jedisPool.getResource();
		try{
			jedis.set(key,value);
			if(this.expire != 0){
				jedis.expire(key, this.expire);
		 	}
		}finally{
			jedis.close();
		}
		return value;
	}
	
	/**
	 * set 
	 * @param key
	 * @param value
	 * @param expire
	 * @return
	 */
	public byte[] set(byte[] key,byte[] value,int expire){
		ShardedJedis jedis = jedisPool.getResource();
		try{
			jedis.set(key,value);
			if(expire != 0){
				jedis.expire(key, expire);
		 	}
		}finally{
			jedis.close();
		}
		return value;
	}
	
	/**
	 * del
	 * @param key
	 */
	public void del(byte[] key){
		ShardedJedis jedis = jedisPool.getResource();
		try{
			jedis.del(key);
		}finally{
			jedis.close();
		}
	}
	
	public void flushDB(){
		ShardedJedis jedis = jedisPool.getResource();
		try{
			Iterator<Jedis> iterator = jedis.getAllShards().iterator();
			while(iterator.hasNext()) {
				iterator.next().flushDB();
			}
		}finally{
			jedis.close();
		}
	}
	
	/**
	 * size
	 */
	public Long dbSize(){
		Long dbSize = 0L;
		ShardedJedis jedis = jedisPool.getResource();
		try{
			Iterator<Jedis> iterator = jedis.getAllShards().iterator();
			while(iterator.hasNext()) {
				dbSize = dbSize+iterator.next().dbSize();
			}
		}finally{
			jedis.close();
		}
		return dbSize;
	}

	/**
	 * keys
	 * @param regex
	 * @return
	 */
	public Set<byte[]> keys(String pattern){
		Set<byte[]> keys = null;
		ShardedJedis jedis = jedisPool.getResource();
		try{
			keys = jedis.hkeys(pattern.getBytes());
		}finally{
			jedis.close();
		}
		return keys;
	}
	
	public int getExpire() {
		return expire;
	}

	public void setExpire(int expire) {
		this.expire = expire;
	}

	public ShardedJedisPool getJedisPool() {
		return jedisPool;
	}

	public void setJedisPool(ShardedJedisPool jedisPool) {
		this.jedisPool = jedisPool;
	}
	
}
